package blue.webserver;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.Exception;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.Headers;


public class HomeHandler implements HttpHandler{
	String file_path_;
	
	public HomeHandler(String path) throws Exception{
		File file = new File(path);
		if (!file.exists()){
			throw new Exception("Invalid file path at "+path);
		}
		file_path_ = path;
	}
	
    public void handle(HttpExchange t) throws IOException {
        // Add the required response header for a PDF file
        Headers h = t.getResponseHeaders();
        h.add("Content-Type", "text/html");

        // Load our client file
        File file = new File (file_path_);
        byte [] bytearray  = new byte [(int)file.length()];
        FileInputStream fis = new FileInputStream(file);
        BufferedInputStream bis = new BufferedInputStream(fis);
        bis.read(bytearray, 0, bytearray.length);

        // Send the response.
        t.sendResponseHeaders(200, file.length());
        OutputStream os = t.getResponseBody();
        os.write(bytearray,0,bytearray.length);
        os.close();
        bis.close();
    }
}